package com.heartunderblade.rpc.observer;

import cn.hutool.json.JSONUtil;
import com.heartunderblade.rpc.Registry.RegistryServiceCache;
import com.heartunderblade.rpc.RpcPojo.ServiceMetaInfo;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class CacheUpdater implements Listener{
    private final RedissonClient redissonClient;
    private final RegistryServiceCache registryServiceCache;

    public CacheUpdater(RedissonClient redissonClient, RegistryServiceCache registryServiceCache) {
        this.redissonClient = redissonClient;
        this.registryServiceCache = registryServiceCache;
    }
    @Override
    public void onCreated(MapEvent event) {
        updateCache(event.getServiceKey());
    }

    @Override
    public void onRemoved(MapEvent event) {
        updateCache(event.getServiceKey());
    }
    // 更新缓存
    private void updateCache(String serviceKey) {
        RMap<String, String> mainMap = redissonClient.getMap(serviceKey);
        List<ServiceMetaInfo> serviceMetaInfos = new ArrayList<>();

        Set<String> keys = mainMap.keySet();
        for (String key : keys) {
            String subKey = serviceKey + "/" + key;
            RBucket<String> subBucket = redissonClient.getBucket(subKey);
            String value = subBucket.get();
            if (value != null) {
                ServiceMetaInfo metaInfo = JSONUtil.toBean(value, ServiceMetaInfo.class);
                serviceMetaInfos.add(metaInfo);
            }
        }
        registryServiceCache.writeCache(serviceKey, serviceMetaInfos);
        System.out.println("Cache updated for serviceKey: " + serviceKey);
    }
}
